{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c82d713d",
   "metadata": {},
   "source": [
    "## 优化百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9abcd683",
   "metadata": {},
   "outputs": [],
   "source": [
    "from asr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7ce08e88",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'FUqWjVBIXj27t7bMhgQQoGWc'\n",
    "SECRET_KEY = 'CqyrSqfDiF0ZcqQ6dGomfYFSHwKaTqnw'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5690dbd5",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 以下为asr代码的优化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "6ee16ed4",
   "metadata": {},
   "outputs": [],
   "source": [
    "#以下被挪到了asr.py\n",
    "# # coding=utf-8\n",
    "\n",
    "# import sys\n",
    "# import json\n",
    "# import time\n",
    "\n",
    "# IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "# if IS_PY3:\n",
    "#     from urllib.request import urlopen\n",
    "#     from urllib.request import Request\n",
    "#     from urllib.error import URLError\n",
    "#     from urllib.parse import urlencode\n",
    "\n",
    "#     timer = time.perf_counter\n",
    "# else:\n",
    "#     import urllib2\n",
    "#     from urllib2 import urlopen\n",
    "#     from urllib2 import Request\n",
    "#     from urllib2 import URLError\n",
    "#     from urllib import urlencode\n",
    "#     if sys.platform == \"win32\":\n",
    "#         timer = time.clock\n",
    "#     else:\n",
    "#         timer = time.time\n",
    "\n",
    "# def fetch_token(API_KEY,SECRET_KEY):\n",
    "#     params = {'grant_type': 'client_credentials',\n",
    "#               'client_id': API_KEY,\n",
    "#               'client_secret': SECRET_KEY}\n",
    "#     post_data = urlencode(params)\n",
    "#     if (IS_PY3):\n",
    "#         post_data = post_data.encode('utf-8')\n",
    "#     req = Request('http://aip.baidubce.com/oauth/2.0/token', post_data)\n",
    "#     try:\n",
    "#         f = urlopen(req)\n",
    "#         result_str = f.read()\n",
    "#     except URLError as err:\n",
    "#         print('token http response http code : ' + str(err.code))\n",
    "#         result_str = err.read()\n",
    "#     if (IS_PY3):\n",
    "#         result_str = result_str.decode()\n",
    "#     result = json.loads(result_str)\n",
    "#     if ('access_token' in result.keys() ):\n",
    "#         return result['access_token']\n",
    "\n",
    "        \n",
    "# def asr(token,AUDIO_FILE='1.wav',CUID='123456PYTHON',DEV_PID='1537',RATE = 16000):\n",
    "#     speech_data = []\n",
    "#     with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "#         speech_data = speech_file.read()\n",
    "#     length = len(speech_data)\n",
    "#     if length == 0:\n",
    "#         raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "\n",
    "#     params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "#     params_query = urlencode(params);\n",
    "\n",
    "#     headers = {\n",
    "#         'Content-Type': 'audio/' + AUDIO_FILE[-3:] + '; rate=' + str(RATE),\n",
    "#         'Content-Length': length\n",
    "#     }\n",
    "\n",
    "#     url = 'http://vop.baidu.com/server_api' + \"?\" + params_query\n",
    "#     req = Request('http://vop.baidu.com/server_api' + \"?\" + params_query, speech_data, headers)\n",
    "#     try:\n",
    "#         begin = timer()\n",
    "#         f = urlopen(req)\n",
    "#         result_str = f.read()\n",
    "#         print(\"Request time cost %f\" % (timer() - begin))\n",
    "#     except  URLError as err:\n",
    "#         print('asr http response http code : ' + str(err.code))\n",
    "#         result_str = err.read()\n",
    "\n",
    "#     if (IS_PY3):\n",
    "#         result_str = str(result_str, 'utf-8')\n",
    "# #     print(result_str)\n",
    "#     with open(\"result.txt\", \"w\") as of:\n",
    "#         of.write(result_str)\n",
    "#     return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ef040e73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.efdc0c54d5afca380edaf8db277b36e7.2592000.1655297158.282335-26238472'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 给使用者使用\n",
    "xie_token=fetch_token(API_KEY,SECRET_KEY)\n",
    "xie_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "344b9a65",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "3564fdc3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.255289\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7098314703529471592\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"您好。\"],\"sn\":\"227598875701652705181\"}\\n'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(token = xie_token,AUDIO_FILE = '1.wav')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "2e15f9df",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.196523\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'您好。'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eval(asr(token = xie_token,AUDIO_FILE = '1.wav'))['result'][0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "354a2c92",
   "metadata": {},
   "source": [
    "## 图灵机器人API测试                  \n",
    "\n",
    "> 1.我说一句话，电脑回复我文本信息          "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "198642cd",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid character in identifier (<ipython-input-2-b3db58d897b2>, line 10)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-2-b3db58d897b2>\"\u001b[1;36m, line \u001b[1;32m10\u001b[0m\n\u001b[1;33m    }，\u001b[0m\n\u001b[1;37m     ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid character in identifier\n"
     ]
    }
   ],
   "source": [
    "def TL_API(TL_key,text)\n",
    "\n",
    "TL_key = ''\n",
    "\n",
    "TL_url = ''\n",
    "\n",
    "payload={\n",
    "    \"redType\":0,\n",
    "    \"perception\":{\n",
    "        \"inputText\":{\n",
    "            \"text\":\"你好\"\n",
    "        }，\n",
    "    }，\n",
    "    \"userInfo\":{\n",
    "        \"apiKey\":TL_key\n",
    "        \"userId\":\"000001\"\n",
    "    }\n",
    "}\n",
    "payload_json = json.dump(payload)\n",
    "res = requests.post(TL_url,headers=headers,data=json.dumps(payload))\n",
    "return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "30c2a33a",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'res' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-1-c08785e04264>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mres\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'res' is not defined"
     ]
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "847a0416",
   "metadata": {},
   "outputs": [],
   "source": [
    "res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1715bb79",
   "metadata": {},
   "source": [
    "## 有图灵接口的语音识别对话机器人               \n",
    "* 目标：我说一句话，电脑回复我文本信息  （TULING_API）\n",
    "> 1.准备音频 -----音频文件（临时文件——时间限制）                   \n",
    "> 2.调用百度语音识别----文本信息（识别到的内容）          \n",
    "> 3.调用图灵机器人----文本信息（智能返回的内容）    \n",
    "                \n",
    "> 4.待做 文本信息语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "347bd135",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "fetch_token() takes 0 positional arguments but 2 were given",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-20-4b6567022211>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     11\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     12\u001b[0m \u001b[1;31m# 2.调用百度语音识别----文本信息（识别到的内容）\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m \u001b[0mxie_token\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mfetch_token\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mAPI_KEY\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mSECRET_KEY\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     14\u001b[0m \u001b[0masr_result\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0meval\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0masr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtoken\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mxie_token\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mAUDIO_FILE\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'1.wav'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'result'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     15\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: fetch_token() takes 0 positional arguments but 2 were given"
     ]
    }
   ],
   "source": [
    "# 准备音频文件\n",
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2.调用百度语音识别----文本信息（识别到的内容）\n",
    "xie_token=fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result = eval(asr(token = xie_token,AUDIO_FILE = '1.wav'))['result'][0]\n",
    "\n",
    "# 3.调用图灵机器人----文本信息（智能返回的内容）\n",
    "\n",
    "TL_API(TL_key,asr_result)\n",
    "\n",
    "# 4.语音合成\n",
    "tts(xie_token,TL_APL(TL_key,asr_result))\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e3fb1c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c8bb54f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "%E6%AC%A2%E8%BF%8E%E4%BD%BF%E7%94%A8%E7%99%BE%E5%BA%A6%E8%AF%AD%E9%9F%B3%E5%90%88%E6%88%90%E3%80%82\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.efdc0c54d5afca380edaf8db277b36e7.2592000.1655297158.282335-26238472&tex=%25E6%25AC%25A2%25E8%25BF%258E%25E4%25BD%25BF%25E7%2594%25A8%25E7%2599%25BE%25E5%25BA%25A6%25E8%25AF%25AD%25E9%259F%25B3%25E5%2590%2588%25E6%2588%2590%25E3%2580%2582&per=4&spd=5&pit=5&vol=5&aue=6&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.wav\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "API_KEY = '4E1BG9lTnlSeIf1NQFlrSq6h'\n",
    "SECRET_KEY = '544ca4657ba8002e3dea3ac2f5fdd241'\n",
    "\n",
    "TEXT = \"欢迎使用百度语音合成。\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 1\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 6\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = xie_token\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "d0c1320f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pydub\n",
      "  Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n",
      "Installing collected packages: pydub\n",
      "Successfully installed pydub-0.25.1\n"
     ]
    }
   ],
   "source": [
    "!pip install pydub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb908afc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
